package com.cx.mall.common.util;

import com.baomidou.mybatisplus.core.toolkit.AES;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EncryptTypeHandler extends BaseTypeHandler<String> {
    // AES密钥 16 位及其倍数
    private static final String AES_KEY = "abcdefgh12345678";
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setString(i, AES.encrypt(parameter,AES_KEY));
        }else {
            ps.setString(i, null);
        }

    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (rs.getString(columnName) != null) {
            return AES.decrypt(rs.getString(columnName),AES_KEY);
        }else {
            return null;
    }}

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
       if (rs.getString(columnIndex) != null) {
            return AES.decrypt(rs.getString(columnIndex),AES_KEY);
        }else {
            return null;
        }
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (cs.getString(columnIndex) != null) {
            return AES.decrypt(cs.getString(columnIndex),AES_KEY);
        }else {
            return null;
        }
    }
}
